package com.flycms.web.system.rest;

import com.flycms.constant.StatusConst;
import com.flycms.core.base.BaseController;
import com.flycms.core.entity.PageVo;
import com.flycms.core.entity.RestDataVo;
import com.flycms.module.article.model.Article;
import com.flycms.module.article.model.ArticleCategory;
import com.flycms.module.article.service.ArticleCategoryRestService;
import com.flycms.module.article.service.ArticleRestService;
import com.flycms.module.message.service.MessageService;
import com.flycms.module.search.service.SolrService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 开发公司：宏石<br/>
 * 版权：宏石<br/>
 *
 * @author sun-kaifei
 * @version 1.0 <br/>
 * @email xxx@qq.com
 * @Date: 10:57 2020/7/13
 */
@RestController
@RequestMapping("/rest/system/article")
@Slf4j
public class ArticleAdminRestController extends BaseController {
    @Autowired
    protected ArticleRestService articleService;
    @Autowired
    protected ArticleCategoryRestService articleCategoryService;
    @Autowired
    private SolrService solrService;
    @Autowired
    protected MessageService messageService;

    /**
     * 文章列表
     *
     * @return
     */
    @GetMapping(value = "/list")
    public RestDataVo getArticleList(@RequestParam(value = "pageIndex", required = false) String pageIndex,
                                     @RequestParam(value = "pageSize", required = false) String pageSize,
                                     @RequestParam(value = "title", required = false) String title,
                                     @RequestParam(value = "status", required = false,defaultValue = "9") Integer status,
                                     @RequestParam(value = "userId", required = false) Long userId,
                                     @RequestParam(value = "typeId", required = false) Long typeId) {
        if (pageIndex == null || !NumberUtils.isNumber(pageIndex)) {
            pageIndex = "1";
        }
        if (pageSize == null || !NumberUtils.isNumber(pageSize)) {
            pageSize = "5";
        }
        if (status == null) {
            status = 9;
        }
        PageVo<Article> page = articleService.getArticleListPage(title, userId, typeId, null, status, null, null, Integer.parseInt(pageIndex), Integer.parseInt(pageSize));
        return RestDataVo.PAGE(page.getList(), Integer.parseInt(pageIndex), Integer.parseInt(pageSize), page.getCount());
    }


    /**
     * 查询单条文章数据信息
     *
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/findId/{id}")
    public RestDataVo getFindArticleId(@PathVariable(value = "id", required = false) String id) {
        RestDataVo data;
        try {
            if (!NumberUtils.isNumber(id)) {
                return RestDataVo.ERROR("id参数错误");
            }
            Article article = articleService.findArticleById(Long.parseLong(id), 0);
            if (article == null) {
                return RestDataVo.ERROR("id错误或不存在！");
            } else {
                return RestDataVo.OK("查询成功", article);
            }
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }


    /**
     * 文章审核操作
     *
     * @return RestDataVo
     * @throws Exception
     */
    @PostMapping("/status")
    @ResponseBody
    public RestDataVo updateArticleStatusById(@RequestBody Article article) throws Exception {
        RestDataVo data;
        Long id = article.getId();
        Integer status = article.getStatus();
        Integer recommend = article.getRecommend();
        try {
            if (id == null) {
                return RestDataVo.ERROR("id参数错误或为空");
            }
            if (status == null) {
                return RestDataVo.ERROR("审核状态参数错误或为空");
            }
            if (recommend == null) {
                recommend = 0;
            }
            data = articleService.updateArticleStatusById(id, status, recommend);
        } catch (Exception e) {
            log.error("异常：" + e);
            data = RestDataVo.ERROR("异常：" + e.getMessage());
        }

        return data;
    }


    /**
     * 保存添加文章
     *
     * @param article
     * @param result
     * @return
     */
    @PostMapping("/article_save")
    @ResponseBody
    public RestDataVo addAdminSave(@RequestBody @Valid Article article, BindingResult result) {
        RestDataVo data;
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    return RestDataVo.ERROR(error.getDefaultMessage());
                }
                return null;
            }
            data = articleService.addArticle(article);
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }


    /**
     * 删除文章
     *
     * @param id
     * @return RestDataVo
     */
    @PostMapping("/del/{id}")
    @ResponseBody
    public RestDataVo deleteArticleById(@PathVariable(value = "id") Long id) throws Exception {
        RestDataVo data;
        try {
            Article article = articleService.findArticleById(id, 9);
            if (article == null) {
                return RestDataVo.ERROR("文章不存在或已被删除");
            }
            if (StatusConst.DELETE.value().equals(article.getStatus())) {
                data = articleService.deleteArticleById(id);
            } else {
                data = articleService.updateArticleStatusById(id, StatusConst.DELETE.value(), 0);
                if (data.getCode() == 200) {
                    messageService.addSystemMessage(0L, article.getUserId(),
                            "管理员删除了您的文章",
                            "您标题为： --" + article.getTitle() + "-- 的文章,因涉及不良信息被管理员删除" +
                                    "，如有疑问请联系管理员。");
                    data = RestDataVo.OK("删除成功");
                }
            }
        } catch (Exception e) {
            log.error("出现异常：" + e);
            data = RestDataVo.ERROR("出现异常：" + e.getMessage());
        }
        return data;
    }


    /**
     * 按父级id查询id下所有分类列表
     *
     * @param parentId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/category_child")
    public List<ArticleCategory> getCategoryChild(@RequestParam(value = "parentId", defaultValue = "0") Long parentId) {
        List<ArticleCategory> list = articleCategoryService.getCategoryListByFatherId(parentId);
        return list;
    }


    /**
     * 查询文章分类
     *
     * @return
     */
    @Deprecated
    @ResponseBody
    @GetMapping(value = "/categorytree")
    public RestDataVo getCategoryAllList() {
        List<ArticleCategory> categoryList = articleCategoryService.getCategoryAllList();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map;
        for (ArticleCategory category : categoryList) {
            map = new HashMap<>(16);
            map.put("id", category.getId());
            map.put("pId", category.getFatherId());
            map.put("name", category.getName());
            list.add(map);
        }
        return RestDataVo.OK(list);
    }

    //添加文章分类
    @GetMapping(value = "/category_add")
    @Deprecated
    public String getAddCategory(ModelMap modelMap) {
        modelMap.addAttribute("admin", getAdminUser());
        return theme.getAdminTemplate("content/add_article_category");
    }


    /**
     * 保存添加文章分类
     *
     * @param pid
     * @param name
     * @return RestDataVo
     */
    @PostMapping("/category_save/{pid}/{name}")
    @ResponseBody
    public RestDataVo AddCategory(@PathVariable(value = "pid", required = false) String pid,
                                  @PathVariable(value = "name", required = false) String name) {
        RestDataVo data;
        try {
            if (StringUtils.isBlank(pid)) {
                return RestDataVo.ERROR("父级分类id不能为空");
            }
            if (!NumberUtils.isNumber(pid)) {
                return RestDataVo.ERROR("父级分类id错误！");
            }
            if (StringUtils.isBlank(name)) {
                return RestDataVo.ERROR("分类名称不能为空");
            }
            data = articleCategoryService.addArticleCategory(Long.parseLong(pid), name);
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }

    /**
     * 编辑文章分类名称
     *
     * @param id
     * @param name
     * @return RestDataVo
     */
    @PostMapping("/category_edit/{id}/{name}")
    @ResponseBody
    public RestDataVo editCategory(@PathVariable(value = "id", required = false) String id,
                                   @PathVariable(value = "name", required = false) String name) {
        RestDataVo data;
        try {
            if (StringUtils.isBlank(id)) {
                return RestDataVo.ERROR("分类id不能为空");
            }
            if (!NumberUtils.isNumber(id)) {
                return RestDataVo.ERROR("分类id错误！");
            }
            if (StringUtils.isBlank(name)) {
                return RestDataVo.ERROR("分类名称不能为空");
            }
            data = articleCategoryService.editArticleCategoryById(Long.parseLong(id), name);
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }

    /**
     * 编辑文章分类所属层级
     *
     * @param id
     * @param pId
     * @return RestDataVo
     */
    @PostMapping("/category_drags/{id}/{pid}")
    @ResponseBody
    public RestDataVo editCategoryDrags(@PathVariable(value = "id", required = false) String id,
                                        @PathVariable(value = "pid", required = false) String pId) {
        RestDataVo data;
        try {
            if (StringUtils.isBlank(id)) {
                return RestDataVo.ERROR("分类id不能为空");
            }
            if (!NumberUtils.isNumber(id)) {
                return RestDataVo.ERROR("分类id错误！");
            }
            if (StringUtils.isBlank(pId)) {
                return RestDataVo.ERROR("未获取到父级id");
            }
            if (!NumberUtils.isNumber(pId)) {
                return RestDataVo.ERROR("父级id错误！");
            }
            data = articleCategoryService.editCategoryDragsById(Long.parseLong(id), Long.parseLong(pId));
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }


    /**
     * 删除文章分类
     *
     * @param id
     * @return RestDataVo
     */
    @PostMapping("/category_delete/{id}")
    @ResponseBody
    public RestDataVo deleteArticleCategoryById(@PathVariable(value = "id", required = false) String id) {
        RestDataVo data;
        try {
            if (StringUtils.isBlank(id)) {
                return RestDataVo.ERROR("分类id不能为空");
            }
            if (!NumberUtils.isNumber(id)) {
                return RestDataVo.ERROR("分类id错误！");
            }
            PageVo<Article> pageVo = articleService.getArticleListPage(null, null, Long.parseLong(id), null, null, null, null, 1, 1);
            if (pageVo.getCount() != 0) {
                return RestDataVo.ERROR("分类下有文章无法删除");
            }
            data = articleCategoryService.deleteArticleCategoryById(Long.parseLong(id));
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }

    /**
     * 全部索引文章
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/index_all_article")
    public RestDataVo indexAllArticle() {
        RestDataVo data;
        try {
            solrService.indexAllArticle();
            data = RestDataVo.ERROR("全部索引成功！");
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }
}
